<?php
/*
 * @Author: KingMin 
 * @Date: 2022-3-12 11:42:04
 * @Last Modified by:   KingMin 
 * @Last Modified time: 2022-3-12 11:42:09
 * @The authors website: https://www.kingmin.cn  
 */
    @require_once '../../init.php';
    @include_once "../common/wxBizDataCrypt.php";
    @include '../common/weixinPay.php';
    // @include_once '../wappewm.php';
    // @include_once '../qrcode.php';
    use GatewayClient\Gateway;
    Gateway::$registerAddress = '127.0.0.1:1238';
    // 获取小程序 ACCESS_TOKEN
    function getwxappaccesstoken(){
        $wechatappid=Option::get('wxappid');
        $wechatappsecre=Option::get('wxappsecre');
        $cache = new MyCache();
        $path=PASH_ROOT."/runtime/wxCache/";
        $cache->dir =$path;//"../../../content/mycache/newadmin/";
        $cache->cacheFile = "wxaccesstoken.json";
        $key='wxappaccesstoken';
        $wxaccesstoken=$cache->getCache($key);
        if($wxaccesstoken){
            return $wxaccesstoken;
        }else{
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$wechatappid."&secret=".$wechatappsecre."";
            $html = file_get_contents($url);
            $html = json_decode($html,true);
            $cache->setCache($key,$html['access_token'],$html['expires_in']);
            return $html['access_token'];
        }
    }
    
    // 获取小程序系统配置
    function getwappconfig($pagePath=''){
        // return $pagePath;
        $navi=Option::getGroup('web_navi');
        $naviList['list']=[];
        if ($pagePath) {
            if($pagePath=='/pages/index/index'){
                $naviList=getnavi();
            }else{
               foreach ($navi as $k =>$v){
                   if($v['pagePath']==$pagePath){
                        $naviList=getnavi();
                        $naviList['naviKey']=$k;
                    }
               }
            }
        }
        
        $iconArray=[
            "permission"=>imgUrlpd("/content/images/icon/permission.png"),
            "zhuxiao"=>imgUrlpd("/content/images/icon/zhuxiao.png"),
            "data"=>imgUrlpd("/content/images/icon/data.png"),
            "message"=>imgUrlpd("/content/images/icon/message.png"),
            "audio_1"=>imgUrlpd("/content/images/icon/audio2b_1.png"),
            "audio_2"=>imgUrlpd("/content/images/icon/audio2b_2.gif"),
            "hi"=>imgUrlpd("/content/images/icon/hi_1.png"),
            "hlqx"=>imgUrlpd("/content/images/icon/hlqx_2.png"),
            "vip_1"=>imgUrlpd("/content/images/icon/vip_1.png"),
            "vip_2"=>imgUrlpd("/content/images/icon/v2-ico.png"),
        ];
        $emojiMap=[
            '[看看]'=> 'emoji_1@25x.gif',
            '[白眼]'=> 'emoji_2@25x.gif',
            '[滚]'=> 'emoji_3@25x.gif',
            '[得意]'=> 'emoji_4@25x.gif',
            '[流鼻血]'=> 'emoji_5@25x.gif',
            '[大哭]'=> 'emoji_6@25x.gif',
            '[NO]'=> 'emoji_7@25x.gif',
            '[玫瑰]'=> 'emoji_8@25x.gif',
        ];
        $emoji=[
            "emojiUrl"=>imgUrlpd("/content/emoji/"),//"https://imgcache.qq.com/open/qcloud/tim/assets/emoji/",
            "emojiMap"=>$emojiMap
        ]; 
        $config= array(
            'dqTime'                    =>              date("Y"),
            'iconArray'                 =>              $iconArray,
            "siteUrl"                   =>              Option::get('siteUrl'),//网站地址
            "naviList"                  =>              $naviList,//小程序底部导航栏
            'index_set'                 =>              json_decode(Option::get('index_set')),//首页设置
            'codeName'                  =>              Option::get('codeName'),//程序名字
            'codeDec'                   =>              Option::get('codeDec'),//程序名字
            'codeLogo'                  =>              Option::get('codeLogo'),//程序LOGO
            'wapplogintime'             =>              Option::get('wapplogintime'),//小程序登录时间/天
            // "yshexy"                    =>              $yshexy,//隐私和协议地址
            "isxy"                      =>              true,//是否显示协议提示,true 不显示 false 显示
            'uploadUrl'                 =>              imgUrlpd("/api/upload"),//附件上传接口
            'checkcode'                 =>              imgUrlpd('/api/admin/code/'.Option::get('codeType')),//登录验证码
            'isCode'                    =>              intval(Option::get('isCode')),//是否开启登录验证码
            'isSmsLogin'                =>              intval(Option::get('isSmsLogin')),//是否开启登录验证码
            'serviceUrl'                =>              "",//客服url地址
            'yszcUrl'                   =>              "",//隐私政策url地址
            'yhxyUrl'                   =>              "",//用户协议url地址
            'loginThemeColor'           =>              Option::get('loginThemeColor'),//登录主题
            'emoji'                     =>              $emoji,//emoji配置
        );
        
        return $config;
    }
    // 获取小程序底部导航栏
    function getnavi(){
        $list=Option::getGroup('web_navi');
        $my="/pages/users/my/index";
        $info="/pages/info/index";
        $user=isLogin(true);
        $uid=$user['uid']??'';
        $infonum= 0;
        
        $mynum=0;
        // if(@$user['msgnumber']){
        //     $mynum=$user['msgnumber'];
        // }
        if($uid){
            // 获取未读信息
            $sxnum=Chat_Model::chatReadCount($uid);
            $infonum+=$sxnum;
            
        }
        
        foreach($list as $k => $v){
            $list[$k]['iconPath']=imgUrlpd($v['iconPath']);
            $list[$k]['selectedIconPath']=imgUrlpd($v['selectedIconPath']);
            $list[$k]['badge']=0;
            if($v['pagePath']==$my){
                $list[$k]['badge']=$mynum;
                // $list[$k]['isDot']=true;
            }
            if($v['pagePath']==$info){
                $list[$k]['badge']=$infonum;
            }
        }
        return array(
            "list"  =>  $list,
            "navi_set"=>Option::get('navi_set')[0]??[]
        );
    }
    
    // 用户注册
    function userRegister($dt){
        if(@!$dt['uname']){
            ajaxReturn (404,"缺失用户名!!!");
        }else{
            $memberKey=User_Model::getMemBerKey(@$dt['uname'],'uname')??true;
            if($memberKey){
                ajaxReturn (205,'用户名已经存在了,请换一个');
            } 
        }
        if(@!$dt['nickName']){
            $dt['nickName']=$dt['uname'];
        }
        if(@!$dt['phone']){
            ajaxReturn (100,'手机号码不能为空');
        }else{
            if(!is_mobile(@$dt['phone'])){
                ajaxReturn (205,'手机号码格式不正确，请检查后提交',$dt);
            }
            $memberKey=User_Model::getMemBerKey(@$dt['phone'],'phone')??true;
            if($memberKey){
                ajaxReturn (205,'手机号码已经存在了，请先解绑,或者更换其他号码');
            }
            if(Option::get("isSms")=='1'){
                if(@!$dt['smsCode']){
                    ajaxReturn (404,'短信验证码为空');
                }
                $iscode=isSmscode($dt['phone'],@$dt['smsCode']);
                if(!$iscode){
                    ajaxReturn(500,'验证码不正确',$dt);
                }
            }
        }
        
        if(@$dt['password']){
            if(@$dt['password']!=@$dt['cfpassword']){
                ajaxReturn(300,'两次输入的密码不一样');
            }
            if(!is_password(@$dt['password'])){
                ajaxReturn (205,'密码强度不够,请换一个,密码必须由字母、数字组成,长度8-18');
            }
            $PHPASS = new PasswordHash(8, true);
            $password=$PHPASS->HashPassword($dt['password']);
            $dt['password']=$password;
        }else{
            ajaxReturn (205,'密码不能为空');
        }
        $os="";
        if(@$dt['os']){
            $os=$dt['os'];
        }
        unset($dt['cfpassword']);
        unset($dt['os']);
        unset($dt['smsCode']);
        $dt['role']='ordinary';
        $up=User_Model::addMemberDetail($dt);
        return $up;
    }
    
    // 获取当前聊天的列表
    function getChatList($dt){
        $user = isLogin();
        return Chat_Model::getChatList($dt, $user['uid']);
    }
    // 获取当前聊天记录的列表
    function getChatDetailsList($dt){
        $user = isLogin();
        return Chat_Model::getChatDetailsList($dt,$user['uid']);
    }
    // 获取用户详情
    function userDetail($uid){
        if(!$uid){
            ajaxReturn (400,'缺失用户ID');
        }
        $user=User_Model::getMemberDetail($uid);
        return $user;
        
    }
    // 发送消息
    function sendMessage($dt){
        $user = isLogin();
        
        @$uid=$user['uid'];
        
        /*if(@!$user['isvip']){
            $tcdata=[
                "path"=>"/pages/users/vip/index",
                "title"=>"提示",
                "content"=>'当前功能只允许会员使用?',
                "cancelColor"=>"#999999",
                "cancelText"=>"取消",
                "confirmColor"=>"#FEA7A8",
                "confirmText"=>"开通会员",
                ];
            ajaxReturn(90099,'会员功能?',$tcdata);
        }*/
        if($dt['type']=='text'){
            $issend=isaddchat($dt);
            if($issend['issend']){
                if($dt['type']=='text'){
                    $dt['payload']['text']=$issend['text'];
                    $dt['payload']['oldtext']=$issend['message']['payload']['text'];
                }
                $dt['read']=0;
                $dt['recalled']=0;
                $dt['status']="success";
                $dt['timestamp']=time()*1000;
                $send=Chat_Model::sendMessage($dt,$uid);
                if($send){
                    $dt['id']=$send;
                    ajaxReturn(200,"发送成功",$dt); 
                }else{
                    return $send;
                }
            }else{
               ajaxReturn(404,$issend['msg'],$issend); 
            }
        }else{
            $dt['read']=0;
            $dt['recalled']=0;
            $dt['status']="success";
            $dt['timestamp']=time()*1000;
            $send=Chat_Model::sendMessage($dt,$uid);
            if($send){
                $dt['id']=$send;
                ajaxReturn(200,"发送成功",$dt); 
            }else{
                return $send;
            }
        }
    }
    
    // 修改聊天详情
    function upChatDetails($dt){
        $user = isLogin();
        $uid=$user['uid'];
        if(!$dt){
            ajaxReturn(404,"参数不存在",$dt); 
        }
        @$id=$dt['id'];
        if(@!$id){
            ajaxReturn(404,"ID参数不存在",$dt);
        }
        unset($dt['id']);
        $detail=Chat_Model::getChatDetails($id);
        if(@$dt['isdel']){
            if(is_array($detail['alldel'])){
                array_push($detail['alldel'],$uid);
                $dt["alldel"]= $detail['alldel'];
            }else{
                $dt['alldel']=[$uid];
            }
            $dt["alldel"]= json_encode($dt["alldel"]);
            unset($dt['isdel']);
        }
        if(@$dt['recalled']){
            $receiverId=$detail['receiverId'];
            if(@$detail['receiverId']==$uid){
                $receiverId=$dt['senderId'];
            }
            $chatData[]=$detail;
            $message=gatewayReturn (200,"recalledChat", '消息撤回',$chatData);
            Chat_Model::sendToUid($receiverId,$message);
        }
        $db = Database::getInstance();
        
        $wSql=" `id`='$id' ";
        $sql=upSqlConvert('sys_chat_details',$dt,$wSql);
            //   return $sql;
        $query = $db->query($sql);
        
        return $query;
    }
    
    // 修改聊天会话列表
    function upChatList($dt){
        $user = isLogin();
        $uid=$user['uid'];
        if(!$dt){
            ajaxReturn(404,"参数不存在",$dt); 
        }
        @$id=$dt['id'];
        if(@!$id){
            ajaxReturn(404,"ID参数不存在",$dt);
        }
        // return $dt;
        unset($dt['id']);
        $db = Database::getInstance();
        
        $wSql=" `id`='$id' ";
        $sql=upSqlConvert('sys_chat',$dt,$wSql);
            //   return $sql;
        $query = $db->query($sql);
        
        return $query;
    }
    
    
    
    
    
    
    
    
    
    
    
    // -------------------------------------------------
    /*
    // 获取我的信息
    function getmydetail(){
        $detail=[];
        // 获取我的菜单列表展示类型
        // $detail['myset']=Option::get('mysettype');
        // $detail['myset']='grid';
        //获取我的菜单列表
        $btnlist=json_decode(Option::get('mybtnlist'),true);
        foreach($btnlist as $k => $v){
            foreach($v['list'] as $kk => $vv)
            $btnlist[$k]['list'][$kk]['icon']=imgUrlpd($vv['icon']);
        }
        $detail['btnlist']=$btnlist;
        //获取我想认识的
        $detail['wxrs']=0;
        //获取关注信息
        $dt['attention']='1';
        $detail['attention']=getattention($dt);
        $detail['attention']=$detail['attention']['pages']['recordCount'];
        // $detail['attention']=0;
        //获取粉丝信息
        $dt['attention']='';
        $detail['fans']=getattention($dt);
        $detail['fans']=$detail['fans']['pages']['recordCount'];
        // $detail['fans']=0;
        // 获取最近访客
        $detail['zjfk']=getzjfklist();
        $detail['zjfk']=$detail['zjfk']['pages']['recordCount'];
        // $detail['zjfk']=0;
        
        return $detail;
        
    }
    
     // 获取最近访客
    function getzjfklist($dt=[]){
        $db = Database::getInstance();
        $user=isLogin();
        @$isAll=$dt['pages']['isAll'];
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
        $wSql="";$mySql='';$isfym="";
        $bySql="ORDER BY update_time DESC ";
	    if(@$user['uid']){
          $mySql="AND `lookid`='".$user['uid']."' ";
        }else{
            return $output;
        }
        $wSql=" AND `type` = '1' " ;
        if(@$dt['type']){
            $mySql="AND `uid`='".$user['uid']."' ";
        }
        $pno = 1;$pgs = intval(Option::get('pagesSize'));
	    if(@$dt['pages']['pno']){
		  $pno = intval($dt['pages']['pno']);
		}
		
		if(@$dt['pages']['pageSize']){
		  $pgs = intval($dt['pages']['pageSize']);
		}
		$output['pages']['pageSize']=$pgs;$output['pages']['pno']=$pno; 
		$totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "user_look` WHERE  `isdel`='0'   $wSql $mySql ";
		$res = $db->fetch_array($db->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "user_look`  WHERE  `isdel`='0'  $wSql $mySql $bySql $isfym ;";
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $v['detail']=[];
            $v['user']=$login->getUserDataByUid($v['uid']);
            $v['typetxt']="未知";
            $v['path']="";
            if($v['type']=='1'){//用户信息
                if(@$dt['type']){
                    $v['detail']=$login->getUserDataByUid($v['lookid']);
                    $v['path']="/pages/users/userhome/index?uid=".$v['lookid'];
                }else{
                    $v['detail']=$login->getUserDataByUid($v['uid']);
                    $v['path']="/pages/users/userhome/index?uid=".$v['uid'];
                }
                $v['typetxt']="用户";
            }
            $v['daytime']=date("Y-m-d", strtotime($v['update_time']));
            $data[]=$v;
        }
        
        $output['list']=$data;
        // $output['sql']=$sql;
        return $output;
    }
    
    // 获取用户小程序的openid
    function getOpenid($code){ // $code为小程序提供
        $appid = Option::get('wxappid'); // 小程序APPID
        $secret  = Option::get('wxappsecre'); // 小程序secret
        if(!$code ){
            ajaxReturn (1000,"缺失请求参数!!!","getOpenid" );
        }
        if(!$appid&&!$secret ){
            ajaxReturn (1000,"缺失小程序appid$appid或appsecret!!!$secret","getOpenid" );
        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';    
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。    
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $r=json_decode($res,true);
        return $r; // 这里是获取到的信息
    }
    
        // 4.获取微信用户绑定的手机号
    function getPhone($dt){
        
        if(!$dt){ajaxReturn (1002,"缺失请求参数!!!","getPhone" );}
        $db = Database::getInstance();
        // return $dt;
        $appid = Option::get('wxappid'); // 小程序APPID
        if(!$appid){
            ajaxReturn (1000,"缺失小程序appid$appid","getPhone" );
        }
        $pc = new WXBizDataCrypt($appid, $dt['pdt']['session_key']);
        $errCode = $pc->decryptData($dt['pdt']['encryptedData'], $dt['pdt']['iv'], $data );
        
        if ($errCode == 0) {
            $user=$dt['user'];
            $data=json_decode($data,true);
            $user['mobile']=$data['phoneNumber'];
            $sql = "SELECT * FROM `" . DB_PREFIX . "user`  WHERE `mobile`='".$data['phoneNumber']."' AND `isdel` !='1' ;";
            $query = $db->query($sql);
            $res = $db->fetch_array($query);
            if(@$res['openid']){
                return getUserLogin($res['openid'],$dt['xt']);
            }else{
                return adduser($user,$dt['xt']);
            }
                
        } else {
           ajaxReturn (404,'获取手机号失败',$errCode ); 
        }
    }
        // 4.获取微信用户绑定的手机号
    function getwappPhone($dt){
        
        if(!$dt){ajaxReturn (1002,"缺失请求参数!!!","getPhone" );}
        $db = Database::getInstance();
        // return $dt;
        
        $wxaccesstoken=getwxappaccesstoken();
        if(!$wxaccesstoken){
            ajaxReturn (300,'ACCESS_TOKEN获取失败','getwappPhone');
        }
        $url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$wxaccesstoken."";
        $data=remote($url,$dt);
        
        if ($data['errcode'] == 0) {
            
            return $data['phone_info'];
                
        } else {
           ajaxReturn (404,'获取手机号失败',$data ); 
        }
    }
    
    // 小程序用户登录
    function getUserLogin($id,$dt=[]){
        if(!$id){ajaxReturn (1002,"缺失请求参数!!!","getUserLogin" );}
        $wapplogintime=intval(Option::get('wapplogintime'));
        $wapplogintime=$wapplogintime*86400;
        $db = Database::getInstance();
        $sql = "SELECT * FROM `" . DB_PREFIX . "user`  WHERE `openid`='$id' AND `isdel` !='1' ;";
        $query = $db->query($sql);
        $res = array();
        $login= new LoginAuth();
        while ($v = $db->fetch_array($query)) {
           if($v['status']=='1'){
               $login->addUserLoginLog('2',$v['uid'],"","",'4',"账号已经被封禁",$dt,$bz="");
               ajaxReturn (500,'账号已经被封禁,请联系平台客服：'.Option::get('pdPhone'),$v['nickName']); 
           }
           $token=[
               'uid'    =>  $v['uid'],
               'time'   =>  time()+$wapplogintime
               ];
           $res=[
               'uid'=>$v['uid'],
               'time'   =>  time()+$wapplogintime,
               'token'=>$login->encrypt(json_encode($token),"E"),
               ];
        }
        if ($res) {
            @$user=$dt['user'];
            if(is_array($user)){
        		@$dt['update_by']=$user['uid'];
        		@$dt['nickName']=filterEmoji($dt['nickName']);
        		
                $Item = array();
                foreach ($user as $key => $data) {
                    $Item[] = "`$key`='$data'";
                }
                $upStr = implode(',', $Item);
                // return $upStr;
                $db = Database::getInstance();
                $sql = "UPDATE `" . DB_PREFIX . "user` SET $upStr  WHERE uid='".$res['uid']."' ;";
                //   return $sql;
                // $query = $db->query($sql);
                
            }
            unset($dt['user']);
            $login->addUserLoginLog('2',$res['uid'],"","",'1',"小程序登录成功",$dt,$bz="");
            return $res;
        } else {
            ajaxReturn (404,'用户不存在'); 
        }
    }
    
    // 过滤掉emoji表情
    function filterEmoji($str) {
        $str = preg_replace_callback("/./u",
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }
    
    // 判断用户的昵称
    function isnickName($name){
        $u= new User_Model();
        $user = isLogin();
        $uid=$user['uid'];
        if($u->isnickNameExist($name,$uid)){
            ajaxReturn (302,'昵称已经存在了，请更换其他的昵称在提交');
        }else{
            return true;
        }
    }
    
    // 用户资料更新
    // 修改用户资料
    function upuser($dt){
        if(!$dt){ajaxReturn(404,'参数为空',$dt);}
        $user = isLogin();
        $uid=$user['uid'];
        $userData=$dt;
        
        if(@!$userData['password']){
            unset($userData['password']);
        }else{
            $PHPASS = new PasswordHash(8, true);
            $userData['password'] = $PHPASS->HashPassword($dt['password']); 
        }
        // return $userData;
        $u= new User_Model();
        
        if(@$userData['mobile']){
            if(!is_mobile($userData['mobile'])){
                ajaxReturn (301,'电话号码格式不正确，请检查后提交');
            }
            $ismobile=$u->isUsermobileExist($userData['mobile'],$uid);
            if($ismobile){
                ajaxReturn (300,'电话号码已经存在了，请先解绑,或者更换其他号码');
            }
        }
        if(@$userData['nickName']){
            if($u->isnickNameExist($userData['nickName'],$uid)){
                ajaxReturn (302,'昵称已经存在了，请更换其他的昵称在提交');
            }
        }
        if(@$userData['avatar']){
            $userData['isavatar']=0;
            $userData['shavatar']=$userData['avatar'];
            unset($userData['avatar']);
        }
        
        $list =$u->updateUser($userData, $uid);
        
        return $list;
    }
    // 修改用户的配置信息
    function setuserconfig($dt){
        if(!$dt){ajaxReturn(404,'参数为空');}
        $user = isLogin();
        $uid=$user['uid'];
        
        $userData=$dt;
        
        // return $dt;
        $Item = array();
        foreach ($dt as $key => $data) {
            $Item[] = "`$key`='$data'";
        }
        $upStr = implode(',', $Item);
        $db = Database::getInstance();
        $sql = "UPDATE `" . DB_PREFIX . "user_config` SET $upStr  WHERE `uid`='$uid' ;";
        //   return $sql;
        $query = $db->query($sql);
        
        if($query){
            return true;
        }else{
            return false;
        }
    }
    
    
    // 6.新增小程序用户
    function adduser($dt,$tt=[]){
        if(!$dt){ajaxReturn (1002,"缺失请求参数!!!","adduser" );}
        $db = Database::getInstance();
        $dt['add_ip']=getIp();
        // $PHPASS = new PasswordHash(8, true);
        // $xcxpassword=Option::get('xcxpassword');
        // $dt['password']=$PHPASS->HashPassword($xcxpassword); 
        @$dt['nickName']=filterEmoji($dt['nickName']);
        @$dt['wxName']=filterEmoji($dt['nickName']);
        $kItem = array();
        $dItem = array();
        foreach ($dt as $key => $data) {
            $kItem[] = $key;
            $dItem[] = $data;
        }
        $field = implode(',', $kItem);
        $values = "'" . implode("','", $dItem) . "'";
        $sql="INSERT INTO `" . DB_PREFIX . "user` ($field) VALUES ($values)";
        // return $sql;
        $user=$db->query($sql);
        $uid=$db->insert_id();
        $notice_number=$db->query("INSERT INTO `" . DB_PREFIX . "notice_number` (`user_id`,`create_by`,`update_by`) VALUES ('$uid','$uid','$uid')");
        $notice_number=$db->query("INSERT INTO `" . DB_PREFIX . "user_matching` (`uid`,`create_by`,`update_by`) VALUES ('$uid','$uid','$uid')");
        $notice_number=$db->query("INSERT INTO `" . DB_PREFIX . "user_config` (`uid`,`create_by`,`update_by`,`photos`,`label`) VALUES ('$uid','$uid','$uid','[]','[]')");
        $notice_number=$db->query("INSERT INTO `" . DB_PREFIX . "membership_user` (`uid`,`end_time`) VALUES ('$uid','".time()."')");
        
        if(@$dt['nickName']){
           $namesql=""; 
        }else{
            if($dt['gender']=='1'){
                $namesql=",`nickName`='微信绅士".$uid."'"; 
            }
            if($dt['gender']=='2'){
                $namesql=",`nickName`='微信女士".$uid."'"; 
            }
        }
        
        $upuser=$db->query("UPDATE `" . DB_PREFIX . "user` SET `create_by`='$uid',`update_by`='$uid'".$namesql." WHERE uid='$uid'");
        // $tkid = $db->insert_id();
        return getUserLogin($dt['openid'],$tt);
    }
    // 获取用户详情
    function gethomeuser($uid,$lat,$lng){
        if(!$uid){
            return false;
        }
        @$loginuser=isLogin(true);
        @$loginuid=$loginuser['uid'];
		if(!$loginuid){
			$loginuid='';
	    }
        $login= new LoginAuth();
        $user=$login->getUserDataByUid($uid);
        //获取关注信息
        $dt['attention']='1';
        $dt['uid']=$uid;
        $attention=getattention($dt);
        $user['attention']=$attention['pages']['recordCount'];
        $user['isattention']=false;
        if($loginuid){
            foreach($attention['list'] as $k => $v){
                if($v['attention_uid']==$loginuid){
                    $user['isattention']=true;
                }
            }
        }
        if($user['gender']=="1"){
            $user['genderico']=imgUrlpd("/content/images/icon/nanico.png");
        }elseif($user['gender']=="2"){
            $user['genderico']=imgUrlpd("/content/images/icon/nvico.png");
        }else{
            $user['genderico']="";
        }
        if($user['isvip']){
            $user['vipico']=[
                "ico"=>imgUrlpd("/content/images/icon/isvip.png"),
                "num"=>103,
                "type"=>"error",
                "path"=>"",
                "message"=>"尊敬的会员用户。",
                ];
            
        }else{
            $user['vipico']=[
                "ico"=>imgUrlpd("/content/images/icon/novip.png"),
                "num"=>103,
                "type"=>"default",
                "path"=>"",
                "message"=>"未开通会员。",
                ];
        }
        // 用户显示的认证信息
        $userrzicon=[];
        
        if($user['isrealName']=='1'){
            $userrzicon[]=[
                "ico"=>imgUrlpd("/content/images/icon/issmrz.png"),
                "num"=>1,
                "path"=>"",
                "name"=>"实名已认证",
                "isrz"=>true,
                "type"=>"success",
                "message"=>"已进行了实名认证,可信度".$user['config']['realName']['reliability'].";".$user['config']['realName']['msg']."。",
                ];
        }else{
            $userrzicon[]=[
                "ico"=>imgUrlpd("/content/images/icon/nosmrz.png"),
                "num"=>101,
                "path"=>"",
                "name"=>"实名未认证",
                "isrz"=>false,
                "type"=>"default",
                "message"=>"用户没有进行实名认证,请谨慎交友。",
                ];
        }
        if($user['iswork']=='1'){
            $userrzicon[]=[
                "ico"=>imgUrlpd("/content/images/icon/isgzrz.png"),
                "num"=>2,
                "path"=>"",
                "name"=>"工作已认证",
                "isrz"=>true,
                "type"=>"success",
                "message"=>"已进行了工作认证,可信度".$user['config']['work']['reliability'].";".$user['config']['work']['msg']."。",
                ];
        }else{
            $userrzicon[]=[
                "ico"=>imgUrlpd("/content/images/icon/nogzrz.png"),
                "num"=>102,
                "path"=>"",
                "name"=>"工作未认证",
                "isrz"=>false,
                "type"=>"default",
                "message"=>"用户没有进行工作认证,请谨慎交友。",
                ];
        }
        if($user['isxueli']=='1'){
            $userrzicon[]=[
                "ico"=>imgUrlpd("/content/images/icon/isxlrz.png"),
                "num"=>3,
                "path"=>"",
                "name"=>"学历已认证",
                "isrz"=>true,
                "type"=>"success",
                "message"=>"已进行了学历认证,可信度".$user['config']['xueli']['reliability'].";".$user['config']['xueli']['msg']."。",
                ];
        }else{
            $userrzicon[]=[
                "ico"=>imgUrlpd("/content/images/icon/noxlrz.png"),
                "num"=>103,
                "path"=>"",
                "name"=>"学历未认证",
                "isrz"=>false,
                "type"=>"default",
                "message"=>"用户没有进行学历认证,请谨慎交友。",
                ];
        }
        $newuserrzicon=array_column($userrzicon, 'num');
        array_multisort($newuserrzicon, SORT_ASC, $userrzicon);
        $user['rzicon']=$userrzicon;
        
        
        //获取粉丝信息
        $dt['attention']='';
        $fans=getattention($dt);
        $user['fans']=$fans['pages']['recordCount'];
        // 用户体系
    	$vipsystem=json_decode(Option::get('vipsystem'),true);
    	$user['vipsystem']=[];
        foreach($vipsystem as $k => $v){
            $v['icon']=imgUrlpd($v['icon']);
            $v['type']="success";
            $v["path"]="";
            $v['message']='当前等级是：'.$v['name'];
            if($user['experience']>=$v['min']&&$user['experience']<=$v['max']){
                $user['vipsystem']=$v;
            }
        }
        $user['ismy']=true;
         $user['tuijshow']=true;
        if($uid!=$loginuid){  
            if(!$lat){
                $lat='29.90496';
            }
            if(!$lng){
                $lng='103.37288';
            }
            $db = Database::getInstance();
            $sql="select (2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*($lng-lng)/360),2)+COS(PI()*$lat/180)* COS(lat * PI()/180)*POW(SIN(PI()*($lat-lat)/360),2)))) as juli  FROM " . DB_PREFIX . "user  WHERE uid = '$uid' ; ";
            
            $res = $db->fetch_array($db->query($sql));
    		$jl = floatval($res['juli']);
            
            
            // return $sql;
            $user['juli']='';
            // if($jl<1000){$jl=$jl;$dw="米";}elseif($jl<10000){$jl=round($jl/1000,2);$dw="km";}else{$jl=round($jl/10000,2);$dw="万米";}
            // @$jl=$v['juli'];
            if($jl){
                $jl=$jl*1000;
                $jl=round($jl,0);
                $dw="米";
                if($jl<1000){$jl=$jl;$dw="m";}else{$jl=round($jl/1000,0);$dw="km";}
                // $user['juli']=$jl;
                // $user['dw']=$dw;
                $user['juli']=$jl.$dw;
            }
            $user['ismy']=false;
            
            if($user['config']['ysconfig']['ycgs']){
                $user['company']="";
            }
            if($user['config']['ysconfig']['ycxx']){
                $user['school']="";
            }
            if($user['config']['ysconfig']['ycwz']){
                $user['juli']="";
            }
            if($user['config']['ysconfig']['bbtrtj']){
                $user['tuijshow']=false;
            }
            if($user['config']['ysconfig']['ysms']){
                $user['tuijshow']=false;
            }
        }else{
            if($user['isavatar']=='0'&&$user['shavatar']){
                array_unshift($user['photolist'],$user['shavatar']);
            }
        }
    	$user['isrecommend']=isrecommend($loginuid,$uid);
    	$user['isshielduser']=isshield($uid,$loginuid,1);
    	$user['isyoushielduser']=isshield($loginuid,$uid,1);
    	
    	
    	
    	
        return $user;
    }
    // 25.获取用户关注信息
    function getattention($dt=[]){
        if(!$dt){ajaxReturn (1002,'参数缺失',"getattention");}
        $db = Database::getInstance();
        $user=isLogin(true);
        @$isAll=$dt['pages']['isAll'];
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
        $wSql="";$mySql='';$isfym="";
        $bySql="ORDER BY create_time DESC ";
	    if(@$user['uid']){
        //   $mySql="AND `uid`='".$user['uid']."' ";
            $uid=$user['uid'];
        }else{
            return $output;
        }
        if(@$dt['uid']){
            $uid=$dt['uid'];
        }
        if(@$dt['attention']){
            $mySql="AND `uid`='".$uid."' ";
        }else{
            $mySql="AND `attention_uid`='".$uid."' ";
        }
        $pno = 1;$pgs = intval(Option::get('pagesSize'));
	    if(@$dt['pages']['pno']){
		  $pno = intval($dt['pages']['pno']);
		}
		
		if(@$dt['pages']['pageSize']){
		  $pgs = intval($dt['pages']['pageSize']);
		}
		$output['pages']['pageSize']=$pgs;$output['pages']['pno']=$pno; 
		$totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "user_attention` WHERE  `isdel`='0'  $wSql $mySql ";
		$res = $db->fetch_array($db->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "user_attention`  WHERE  `isdel`='0'   $wSql $mySql $bySql $isfym ;";
        $logs = $db->query($sql);
        $data = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $v['user']=$login->getUserDataByUid($v['uid']);
            $v['attentionuser']=$login->getUserDataByUid($v['attention_uid']);
            if(@$dt['attention']){
                $v['userdata']=$v['attentionuser'];
            }else{
                 $v['userdata']=$v['user'];
                 $sql = "SELECT * FROM  `" . DB_PREFIX . "user_attention` WHERE `isdel`='0' AND `uid`='$uid' AND `attention_uid`='".$v['user']['uid']."' ;";
                //  $v['sql']=$sql;
                 $isgz=false;
                 $gzlt = $db->query($sql);
                 foreach ($gzlt as $i => $d) {
                   $isgz=true;
                 }
                 $v['userdata']['isattention']=$isgz;
            }
            $data[]=$v;
        }
        
        $output['list']=$data;
        // $output['sql']=$sql;
        return $output;
    }
    
    // 新增用户关注
    
    function addattention($id){
        if(!$id){return false;}
        $user=isLogin();
        if(@!$user['uid']){
            return false;
        }else{
            $uid=$user['uid'];
        }
        if($uid==$id){
            ajaxReturn(202,'不能自己关注自己',$id);
        }
        $db = Database::getInstance();
        $sql = "SELECT * FROM  `" . DB_PREFIX . "user_attention` WHERE  `uid`='$uid' AND `attention_uid`='$id' ;";
        $logs = $db->query($sql);
        $list=[];
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $list=$v;
        }
        if(@$list['uid']){
            if($list['isdel']=='0'){
                $db->query('UPDATE '.DB_PREFIX."user_attention SET `isdel`='1' WHERE `uid`='$uid' AND `attention_uid`='$id' ");
            }else{
                $db->query('UPDATE '.DB_PREFIX."user_attention SET `isdel`='0' WHERE `uid`='$uid' AND `attention_uid`='$id' ");
            }
            return true;
        }else{
            $dt['attention_uid']=$id;
            $dt['uid']=$uid;
            $kItem = array();
            $dItem = array();
            foreach ($dt as $key => $data) {
                $kItem[] = $key;
                $dItem[] = $data;
            }
            $field = implode(',', $kItem);
            $values = "'" . implode("','", $dItem) . "'";
            $sql="INSERT INTO `" . DB_PREFIX . "user_attention` ($field) VALUES ($values)";
            // return $sql;
            $baby=$db->query($sql);
            // $id=$db->insert_id();
            return true;
        }
    } 
    // 获取图片详情
    function imagesdetails($id){
        $db = Database::getInstance();
        
        $sql = "SELECT * FROM `" . DB_PREFIX . "upload` WHERE `id`='$id' ;";
        $logs = $db->query($sql);
        
        $data = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $v['remark']=json_decode($v['remark'],true);
            if($v['type']=='1'){
                $v['info']=[
                    "size"=>$v['fsize'],
                    "format"=>$v['remark']['format'],
                    "width"=>intval($v['remark']['width']),
                    "height"=>intval($v['remark']['height'])
                ];
            }
            $data=$v;
        }
        
        return $data;
    }
        // 删除图片
    function detImg($url){
        $user=isLogin();
        if(!$url){
            ajaxReturn(404,'参数为空');
        }else{
            if($url=='null'){
               ajaxReturn(200,'删除成功');
            }
            $pos = strpos($url, "/images/");
            if(!$pos){
                $d=detImg1($url);
                ajaxReturn(200,'删除成功');
            }
            $imgid=substr($url,$pos+8);
            $imgid=intval($imgid);
            $imgdt=imagesdetails($imgid);
            // ajaxReturn(404,'参数为空',$pos);
            if($imgdt['isuptp']=='1'){
                $url=$imgdt['url'];
                $pos = strpos($url, "/content");
                $pic=PASH_ROOT.substr($url,$pos);
                if(file_exists($pic)){
                $res = unlink($pic);
                    if($res){
    					$output["code"]=200;$output["msg"]='删除成功';
                    }else{
                        $output["code"]=1003;$output["msg"]='操作失误导致图片或文件无法删除';
                    }
                }else{
                    $output["code"]=1003;$output["msg"]='无法找到文件或者已经删除'.$pic;
                }
            }
            if($imgdt['isuptp']=='2'){
                $url=$imgdt['url'];
                $pos = strpos($url, "/uploadfile/");
                $pic=substr($url,$pos+1);
                $sctp=deleteOldQiniu($pic);
                $output["code"]=200;$output["msg"]='删除成功';$output['data']=$sctp;
            }
            $db = Database::getInstance();
            $db->query('UPDATE '.DB_PREFIX."upload SET `isdel`='1' WHERE `id`='$imgid' ");
            
            return $output;
        }
        
    }
        // 删除图片 方法备份
    function detImg1($url){
        $user=isLogin();
        if(!$url){
            ajaxReturn(404,'参数为空');
        }else{
            if($url=='null'){
               ajaxReturn(200,'删除成功');
            }
            @$qiniuyun=json_decode(Option::get('qiniuyun'),true);
            @$qnurl=$qiniuyun['url'];
            $isqn = strpos($url, $qnurl);
            
            if($isqn){
                $pos = strpos($url, "/uploadfile/");
                $pic=substr($url,$pos+1);
                $sctp=deleteOldQiniu($pic);
                $output["code"]=200;$output["msg"]='删除成功';$output['data']=$sctp;
            }else{
                $pos = strpos($url, "/content");
                $pic=PASH_ROOT.substr($url,$pos);
                if(file_exists($pic)){
                $res = unlink($pic);
                    if($res){
    					$output["code"]=200;$output["msg"]='删除成功';
                    }else{
                        $output["code"]=1003;$output["msg"]='操作失误导致图片或文件无法删除';
                    }
                }else{
                    $output["code"]=1003;$output["msg"]='无法找到文件或者已经删除'.$pic;
                }
               
            }
            return $output;
        }
        
    }
    //七牛删除图片
    function deleteOldQiniu($filenames) {
        $qiniuyun=json_decode(Option::get('qiniuyun'),true);
        if(!$qiniuyun){
            return false;
        }else {
             @$accessKey=$qiniuyun['accesskey'];
             @$secretKey=$qiniuyun['secretkey'];
             @$bucket=$qiniuyun['bucket'];
             @$url=$qiniuyun['url'];
        }
        $auth = new Qiniu\Auth($accessKey, $secretKey);
        $config = new Qiniu\Config();
        $bucketManager = new Qiniu\Storage\BucketManager($auth, $config);
        //删除图片的名称
        $key = $filenames;
        $err = $bucketManager->delete($bucket, $key);
        if ($err) {
            return $err;
        }else {
            return true;
        }
    }
    // 删除多张图片
    
    function detltimg($dt){
        $user = isLogin();
        if(!$dt){ajaxReturn(404,'参数为空');}
        foreach ( $dt as $k => $v){
            $va=detImg($v);
            if($va['code']!=200){
                ajaxReturn($va["code"],$va["msg"],$va);
            }
        }
        return true;
    }
    
    // 小程序添加用户浏览记录
    function adduserlook($uid,$type,$id){
        if(!$id||!$uid||!$type){return false;}
        
        $db = Database::getInstance();
        $sql = "SELECT * FROM  `" . DB_PREFIX . "user_look` WHERE  `uid`='$uid' AND `type`='$type' AND `lookid`='$id' ;";
        $logs = $db->query($sql);
        $list=[];
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $list=$v;
        }
        if(@$list['uid']){
            if($list['isdel']=='0'){
                $db->query('UPDATE '.DB_PREFIX."user_look SET `number`=number+1,`isdel`='0' WHERE `uid`='$uid' AND `type`='$type' AND `lookid`='$id' ");
            }else{
                $db->query('UPDATE '.DB_PREFIX."user_look SET `number`=number+1,`isdel`='0' WHERE `uid`='$uid' AND `type`='$type' AND `lookid`='$id' ");
            }
            return true;
        }else{
            $dt['lookid']=$id;
            $dt['update_by']=$uid;
            $dt['uid']=$uid;
            $dt['type']=$type;
            $dt['number']=1;
            $kItem = array();
            $dItem = array();
            foreach ($dt as $key => $data) {
                $kItem[] = $key;
                $dItem[] = $data;
            }
            $field = implode(',', $kItem);
            $values = "'" . implode("','", $dItem) . "'";
            $sql="INSERT INTO `" . DB_PREFIX . "user_look` ($field) VALUES ($values)";
            // return $sql;
            $baby=$db->query($sql);
            // $id=$db->insert_id();
            // $mg=[];
            // $mg['list']=$list;
            // $mg['dt']=$dt;
            // $mg['sql']=$sql;
            
            // file_put_contents($_SERVER['DOCUMENT_ROOT']."/content/log/userlook.txt",json_encode($mg).PHP_EOL,FILE_APPEND);//记录日志
            return true;
        }
    }
    
    // 获取用户浏览记录
    function getuserlooklist($dt=[]){
        $db = Database::getInstance();
        $user=isLogin(true);
        @$isAll=$dt['pages']['isAll'];
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
        $wSql="";$mySql='';$isfym="";
        $bySql="ORDER BY update_time DESC ";
	    if(@$user['uid']){
          $mySql="AND `uid`='".$user['uid']."' ";
        }else{
            return $output;
        }
        if(@$dt['type']){
            $wSql=" AND `type` = ".$dt['type']." " ;
        }
        
        $pno = 1;$pgs = intval(Option::get('pagesSize'));
	    if(@$dt['pages']['pno']){
		  $pno = intval($dt['pages']['pno']);
		}
		
		if(@$dt['pages']['pageSize']){
		  $pgs = intval($dt['pages']['pageSize']);
		}
		$output['pages']['pageSize']=$pgs;$output['pages']['pno']=$pno; 
		$totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "user_look` WHERE  `isdel`='0'   $wSql $mySql ";
		$res = $db->fetch_array($db->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "user_look`  WHERE  `isdel`='0'  $wSql $mySql $bySql $isfym ;";
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $v['detail']=[];
            $v['user']=$login->getUserDataByUid($v['uid']);
            $v['typetxt']="未知";
            $v['path']="";
            if($v['type']=='1'){//用户信息
                $v['detail']=$login->getUserDataByUid($v['lookid']);
                $v['typetxt']="用户";
                $v['path']="/pages/users/userhome/index?uid=".$v['lookid'];
            }
            if($v['type']=='2'){//文章信息
                $v['detail']=getarticledetail($v['lookid'],false,true);
                $v['typetxt']="文章";
                $v['path']="/pages/plugin/article?id=".$v['lookid'];
            }
            if($v['type']=='3'){//圈子信息
                $v['detail']=getbooksreadDt($v['lookid'],false);
                $v['typetxt']="圈子";
                $v['path']="/pages/discover/detail/index?id=".$v['lookid'];
            }
            if($v['type']=='4'){//活动信息
                $v['typetxt']="活动";
            }
            if($v['type']=='5'){//书籍信息
            
                $books=beasbooksdetail($v['lookid']);
                $books['isread']=getisread($v['uid'],$v['lookid']);
                $books['iscart']=isstore_cart($v['uid'],$v['lookid']);
                $v['detail']= $books;
                $v['typetxt']="书籍";
                $v['path']="/pages/books/detail/index?id=".$v['lookid'];
            }
            if($v['type']=='6'){//积分商品信息
                $v['detail']=getgoodsdetail($v['lookid'],true);
                $v['typetxt']="商品";
                $v['path']="/pages/integral/goods/details?id=".$v['lookid'];
            }
            
            $v['daytime']=date("Y-m-d", strtotime($v['update_time']));
            $data[]=$v;
        }
        
        $output['list']=$data;
        // $output['sql']=$sql;
        return $output;
    }
    
    // 判断本周是否已经推荐了
    function isrecommend($uid,$id){
        if(!$id||!$uid){return false;}
        $zhouy=date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
        $db = Database::getInstance();
        $sql = "SELECT * FROM  `" . DB_PREFIX . "user_recommend` WHERE  `uid`='$id' AND `create_by`='$uid' AND `create_time`>='$zhouy' ;";
        $logs = $db->query($sql);
        $list=[];
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $list=$v;
        }
        if(@$list['uid']){
            return true;
        }else{
            return false;
        }
    }
    
    //添加周推荐信息
    function addrecommend($id){
        if(!$id){return false;}
        $zhouy=date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
        $user=isLogin();
        if(@!$user['uid']){
            return false;
        }else{
            $uid=$user['uid'];
        }
        if($id==$uid){
            ajaxReturn(202,'不能自己推荐自己',$total);
        }
        $db = Database::getInstance();
        $sql = "SELECT * FROM  `" . DB_PREFIX . "user_recommend` WHERE  `uid`='$id' AND `create_by`='$uid' AND `create_time`>='$zhouy' ;";
        // return $sql;
        $logs = $db->query($sql);
        $list=[];
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $list=$v;
        }
        if(@$list['uid']){
            ajaxReturn(201,'本周已经推荐了,请下周再来','');
        }else{
            $sql="INSERT INTO `" . DB_PREFIX . "user_recommend`(`uid`,`create_by`, `update_by`) VALUES ('$id','$uid','$uid')";
            // return $sql;
            $logs = $db->query($sql);
            
            $totalSql = "SELECT COUNT(*) as total FROM  `" . DB_PREFIX . "user_recommend` WHERE  `uid`='$id' AND `create_time`>='$zhouy' ;";
            // return $sql;
            $res = $db->fetch_array($db->query($totalSql));
    		$total = intval($res['total']);
    		
    		ajaxReturn(200,'推荐成功了,你是本周第'.$total.'个推荐Ta的人',$total);
        }
    }
    
     // 获取推荐我的用户
    function getrecommend($dt=[]){
        $db = Database::getInstance();
        $zhouy=date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
        $shangz=date('Y-m-d', strtotime('-2 monday', time()));
        $user=isLogin();
        @$isAll=$dt['pages']['isAll'];
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
        $wSql="";$mySql='';$isfym="";
        $bySql="ORDER BY update_time DESC ";
	    if(@$user['uid']){
          $mySql="AND `uid`='".$user['uid']."' ";
        }else{
            return $output;
        }
        if(@$dt['type']==1){
            $wSql=" AND `create_time`>='$zhouy' ";
        }elseif(@$dt['type']==2){
            $wSql=" AND `create_time`>='$shangz'  AND `create_time`<'$zhouy' ";
        }else{
            $wSql="";
        }
        
        $pno = 1;$pgs = intval(Option::get('pagesSize'));
	    if(@$dt['pages']['pno']){
		  $pno = intval($dt['pages']['pno']);
		}
		
		if(@$dt['pages']['pageSize']){
		  $pgs = intval($dt['pages']['pageSize']);
		}
		$output['pages']['pageSize']=$pgs;$output['pages']['pno']=$pno; 
		$totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "user_recommend` WHERE  `isdel`='0'   $wSql $mySql ";
		$res = $db->fetch_array($db->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "user_recommend`  WHERE  `isdel`='0'  $wSql $mySql $bySql $isfym ;";
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $v['user']=$login->getUserDataByUid($v['uid']);
            $v['userdata']=$login->getUserDataByUid($v['create_by']);
            $sql = "SELECT * FROM  `" . DB_PREFIX . "user_attention` WHERE `isdel`='0' AND `uid`='".$user['uid']."' AND `attention_uid`='".$v['userdata']['uid']."' ;";
                 $v['sql']=$sql;
            $isgz=false;
            $gzlt = $db->query($sql);
            foreach ($gzlt as $i => $d) {
                $isgz=true;
            }
                 $v['userdata']['isattention']=$isgz;
            $data[]=$v;
        }
        
        $output['list']=$data;
        // $output['sql']=$sql;
        return $output;
    }
    
    // 新增投诉举报信箱
    function addreport($dt=[]){
        if(!is_array($dt)||!$dt){
            ajaxReturn(400,"参数为空",$dt);
        }
        $user = isLogin();
        @$report_id=$dt['report_id'];
        @$type=$dt['type'];
        @$select=$dt['select'];
        if($user['uid']==$report_id){
            ajaxReturn(202,'你要举报自己吗?',$report_id);
        }
        $db = Database::getInstance();
        $sql = "SELECT * FROM  `" . DB_PREFIX . "report` WHERE  `report_id`='$report_id' AND `type`='$type' AND `select`='$select' AND `status`='0' AND `isdel`='0';";
        
        // ajaxReturn(400,"参数为空",$sql);
        $logs = $db->query($sql);
        $list=[];
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $list=$v;
        }
        if(@$list['create_by']){
            ajaxReturn(200,"已经举报过了,请耐心等候客服处理",$list);
        }
        
        $dt['create_by']=$user['uid'];
        
        $kItem = array();
        $dItem = array();
        foreach ($dt as $key => $data) {
            $kItem[] = '`'.$key.'`';
            $dItem[] = $data;
        }
        $field = implode(',', $kItem);
        $values = "'" . implode("','", $dItem) . "'";
        $sql="INSERT INTO `" . DB_PREFIX . "report` ($field) VALUES ($values)";
        // ajaxReturn(400,"参数为空",$sql);
        // return $sql;
        $baby=$db->query($sql);
        // $id=$db->insert_id();
        return true;
    }
    
    // 判读是否屏蔽
    
    function isshield($uid,$shield_id,$type){
        if(!$uid||!$shield_id){
            return false;
        }
        $db = Database::getInstance();
        $sql = "SELECT * FROM  `" . DB_PREFIX . "shield` WHERE  `shield_id`='$shield_id' AND `type`='$type' AND `uid`='$uid' AND `isdel`='0';";
        
        // ajaxReturn(400,"参数为空",$sql);
        $logs = $db->query($sql);
        $list=[];
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $list=$v;
        }
        if(@$list['uid']){
            return true;
        }else{
            return false;
        }
    }
    
    // 新增屏蔽信息
    function addshield($dt=[]){
        if(!is_array($dt)||!$dt){
            ajaxReturn(400,"参数为空",$dt);
        }
        $user = isLogin();
        @$shield_id=$dt['shield_id'];
        @$type=$dt['type'];
        @$uid=$user['uid'];
        if($uid==$shield_id){
            ajaxReturn(202,'你要屏蔽自己吗?',$shield_id);
        }
        $db = Database::getInstance();
        $sql = "SELECT * FROM  `" . DB_PREFIX . "shield` WHERE  `shield_id`='$shield_id' AND `type`='$type' AND `uid`='$uid' AND `isdel`='0';";
        
        // ajaxReturn(400,"参数为空",$sql);
        $logs = $db->query($sql);
        $list=[];
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $list=$v;
        }
        if(@$list['uid']){
            return true;
        }
        
        $dt['create_by']=$user['uid'];
        $dt['uid']=$user['uid'];
        
        $kItem = array();
        $dItem = array();
        foreach ($dt as $key => $data) {
            $kItem[] = '`'.$key.'`';
            $dItem[] = $data;
        }
        $field = implode(',', $kItem);
        $values = "'" . implode("','", $dItem) . "'";
        $sql="INSERT INTO `" . DB_PREFIX . "shield` ($field) VALUES ($values)";
        // ajaxReturn(400,"参数为空",$sql);
        // return $sql;
        $baby=$db->query($sql);
        // $id=$db->insert_id();
        return true;
    }
    
    // 取消屏蔽信息
    function upshield($dt=[]){
         if(!$dt){ajaxReturn(404,'参数为空');}
        $user = isLogin();
        @$uid=$user['uid'];
        if(!$uid){ajaxReturn(404,'参数为空,UID');}
        $id=$dt['id'];
        if(!$id){ajaxReturn(404,'参数为空,ID');}
        
        $userData=$dt;
        unset($userData['id']);
        // return $dt;
        $Item = array();
        foreach ($userData as $key => $data) {
            $Item[] = "`$key`='$data'";
        }
        $upStr = implode(',', $Item);
        $db = Database::getInstance();
        $sql = "UPDATE `" . DB_PREFIX . "shield` SET $upStr  WHERE `uid`='$uid' AND `id`='$id' ;";
        //   return $sql;
        $query = $db->query($sql);
        
        if($query){
            return true;
        }else{
            return false;
        }
    }
    
    // 获取用户屏蔽信息
    function getshieldlist($dt=[],$uid=''){
        $db = Database::getInstance();
        if(!$uid){
            $user=isLogin();
            $uid=$user['uid'];
        }
        @$isAll=$dt['pages']['isAll'];
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
        $wSql="";$mySql='';$isfym="";
        $bySql="ORDER BY update_time DESC ";
	    if(@$uid){
          $mySql="AND `uid`='".$uid."' ";
        }else{
            return $output;
        }
        if(@$dt['type']){
            $wSql=" AND `type` = ".$dt['type']." " ;
        }else{
            return $output;
        }
        
        $pno = 1;$pgs = intval(Option::get('pagesSize'));
	    if(@$dt['pages']['pno']){
		  $pno = intval($dt['pages']['pno']);
		}
		
		if(@$dt['pages']['pageSize']){
		  $pgs = intval($dt['pages']['pageSize']);
		}
		$output['pages']['pageSize']=$pgs;$output['pages']['pno']=$pno; 
		$totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "shield` WHERE  `isdel`='0'   $wSql $mySql ";
		$res = $db->fetch_array($db->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "shield`  WHERE  `isdel`='0'  $wSql $mySql $bySql $isfym ;";
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data = array();
        $uiddata = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $v['user']=$login->getuserByUid($v['shield_id']);
            $data[]=$v;
            $uiddata[]=$v['shield_id'];
        }
        
        $output['list']=$data;
        $output['uidlist']=$uiddata;
        // $output['sql']=$sql;
        return $output;
    }
    
        
    // 新增牵线申请
    function adduserpull($id){
        if(!$id){
            ajaxReturn(400,"参数为空",$id);
        }
        $user = isLogin();
        @$uid=$user['uid'];
        if($uid==$id){
            ajaxReturn(202,'你要和自己牵线吗?',$id);
        }
        if(!$user['isvip']){
            $tcdata=[
                "path"=>"/pages/users/vip/index",
                "title"=>"提示",
                "content"=>'会员才可以享用红娘牵线的权益?',
                "cancelColor"=>"#999999",
                "cancelText"=>"再看看",
                "confirmColor"=>"#FEA7A8",
                "confirmText"=>"开通会员",
                ];
            ajaxReturn(90099,'会员才可以享用红娘牵线的权益?',$tcdata);
        }
        $db = Database::getInstance();
        $sql = "SELECT * FROM  `" . DB_PREFIX . "user_pull` WHERE  `pull_id`='$id' AND `uid`='$uid' AND `isdel`='0';";
        
        // ajaxReturn(400,"参数为空",$sql);
        $logs = $db->query($sql);
        $list=[];
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $list=$v;
        }
        if(@$list['id']){
            ajaxReturn(400,"请勿多次申请",$sql);
        }
        
        // 扣除会员次数
        if($user['vip_number']>0){
            $sql = "UPDATE `" . DB_PREFIX . "membership_user` SET `number`=number-1  WHERE `isdel`='0' AND uid='".$uid."' ;";
            //   return $sql;
            $query = $db->query($sql);
        }else{
            $tcdata=[
                "path"=>"/pages/users/vip/index",
                "title"=>"提示",
                "content"=>'红娘牵线次数不足?',
                "cancelColor"=>"#999999",
                "cancelText"=>"取消",
                "confirmColor"=>"#FEA7A8",
                "confirmText"=>"购买次数",
                ];
            ajaxReturn(90099,'红娘牵线次数不足?',$tcdata);
        }
        
        $dt['pull_id']=$id;
        $dt['update_by']=$user['uid'];
        $dt['uid']=$user['uid'];
        
        $kItem = array();
        $dItem = array();
        foreach ($dt as $key => $data) {
            $kItem[] = '`'.$key.'`';
            $dItem[] = $data;
        }
        $field = implode(',', $kItem);
        $values = "'" . implode("','", $dItem) . "'";
        $sql="INSERT INTO `" . DB_PREFIX . "user_pull` ($field) VALUES ($values)";
        // ajaxReturn(400,"参数为空",$sql);
        // return $sql;
        $baby=$db->query($sql);
        // $id=$db->insert_id();
        return true;
    }
    
    // 获取会员卡列表
    function getviplist(){
        $db = Database::getInstance();
        
        $list = array();
        
        $sql = "SELECT * FROM `" . DB_PREFIX . "membership` WHERE  `isdel`='0' ORDER BY paixu ASC,price ASC ;";
        $logs = $db->query($sql);
        
        foreach ($logs as $key => $v) {
            $typeday=1;$showday='';
            if($v['validity_type']=='1'){
                $typeday=1;
                $showday=$v['validity'].'天';
            }
            if($v['validity_type']=='2'){
                $typeday=30;
                $showday=$v['validity'].'个月';
            }
            if($v['validity_type']=='3'){
                $typeday=365;
                $showday=$v['validity'].'年';
            }
            $v['bg']=imgUrlpd($v['bg']);
            $v['day']=intval($v['validity'])*$typeday;
            $v['original']=number_format($v['original'],2);
            $v['price']=number_format($v['price'],2);
            $v['number']=intval($v['number']);
            $v['showday']=$showday;
            $list[]=$v;
        }
        
        return $list;
    }
    // 获取会员详情
    function getviplistdt($id){
        $db = Database::getInstance();
        
        $list = array();
        
        $sql = "SELECT * FROM `" . DB_PREFIX . "membership` WHERE  `isdel`='0' AND `id`='".$id."' ;";
        $logs = $db->query($sql);
        
        foreach ($logs as $key => $v) {
            $typeday=1;$showday='';
            if($v['validity_type']=='1'){
                $typeday=1;
                $showday=$v['validity'].'天';
            }
            if($v['validity_type']=='2'){
                $typeday=30;
                $showday=$v['validity'].'个月';
            }
            if($v['validity_type']=='3'){
                $typeday=365;
                $showday=$v['validity'].'年';
            }
            $v['bg']=imgUrlpd($v['bg']);
            $v['day']=intval($v['validity'])*$typeday;
            $v['original']=number_format($v['original'],2);
            $v['price']=number_format($v['price'],2);
            $v['number']=intval($v['number']);
            $v['showday']=$showday;
            $list=$v;
        }
        
        return $list;
    }
    
    // 判断是否可以发送消息
    function isaddchat($dt){
        if(!is_array($dt)||!$dt){
            ajaxReturn(400,"参数为空",$dt);
        }
        $user = isLogin();
        
        @$uid=$user['uid'];
        
        if(@$user['isvip']){
            $tcdata=[
                "path"=>"/pages/users/vip/index",
                "title"=>"提示",
                "content"=>'当前功能只允许会员使用?',
                "cancelColor"=>"#999999",
                "cancelText"=>"取消",
                "confirmColor"=>"#FEA7A8",
                "confirmText"=>"开通会员",
                ];
            ajaxReturn(90099,'会员功能?',$tcdata);
        }
        $msg="包含电话号码";
        $text="";
        $issend=true;
        if($dt['type']=='text'){
            $text=$dt['payload']['text'];
            $phone=findThePhoneNumbers($text);
            
            $sensitive=isSensitive($text);
            if($sensitive['count']>0){
                $issend=$sensitive['send'];
                $text=$sensitive['stringAfter'];
                $msg="包含敏感词【".$sensitive['sensitiveWord']."】";
            }
        }
        $rddata=[
                "issend"=>$issend,
                "message"=>$dt,
                "istel"=>$phone,
                "text"=>$text,
                "msg"=>$msg,
                "sensitive"=>$sensitive,
                "list"=>sensitiveList()
            ];
        return $rddata;
    }
    
    // 新增聊天记录
    function addgoeasy($dt){
        if(!is_array($dt)||!$dt){
            ajaxReturn(400,"参数为空",$dt);
        }
        $user = isLogin();
        
        @$uid=$user['uid'];
        $dt['create_by']=$uid;
        $dt['update_by']=$uid;
        
        if(@$dt['payload']){
           $dt['payload']=emoji_encode($dt['payload']);
        }
        
        $db = Database::getInstance();
        
        $kItem = array();
        $dItem = array();
        foreach ($dt as $key => $data) {
            $kItem[] = '`'.$key.'`';
            $dItem[] = $data;
        }
        $field = implode(',', $kItem);
        $values = "'" . implode("','", $dItem) . "'";
        $sql="INSERT INTO `" . DB_PREFIX . "chat_goeasy` ($field) VALUES ($values)";
        // ajaxReturn(400,"参数为空",$sql);
        // return $sql;
        $baby=$db->query($sql);
        $id=$db->insert_id();
        $dt['first']=$id;
        $dt['last']=$id;
        addchatlist($dt);
        return true;
    }
    // 添加会话列表
    function addchatlist($dt){
        if(!is_array($dt)||!$dt){
            ajaxReturn(400,"参数为空",$dt);
        }
        $user = isLogin();
        
        @$uid=$user['uid'];
        if(@$dt['receiverId']){
            $receiverId=$dt['receiverId'];
            unset($dt['receiverId']);
        }else{
            ajaxReturn(404,'参数为空');
        }
        if(@$dt['senderId']){
            $senderId=$dt['senderId'];
            unset($dt['senderId']);
        }else{
            ajaxReturn(404,'参数为空');
        }
        $db = Database::getInstance();
        
        $mySql=" AND ( `receiverId`='$receiverId' OR `senderId`='$receiverId' )  AND ( `receiverId`='$senderId' OR `senderId`='$senderId' )  ";
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "chat_goeasy_list` WHERE 1 $mySql ;";
        
        // ajaxReturn(400,"参数为空",$sql);
        $logs = $db->query($sql);
        $list=[];
        foreach ($logs as $key => $v) {
            $v['time']=smartDate(strtotime($v['create_time']));
            $list=$v;
        }
        if(@$list['id']){
            $db->query('UPDATE `'.DB_PREFIX."chat_goeasy_list` SET `isdel`='0',`views`=views+1,`receiverdel`='0',`senderdel`='0',`last`='".$dt['last']."'  WHERE `id`='".$list['id']."' ");
            return true;
        }else{
            $addt=[
                "create_by"=>$uid,
                "update_by"=>$uid,
                "receiverId"=>$receiverId,
                "senderId"=>$senderId,
                "first"=>$dt['first'],
                "last"=>$dt['last'],
                "chattype"=>$dt['chattype'],
                "views"=>1
                ];
            
            $kItem = array();
            $dItem = array();
            foreach ($addt as $key => $data) {
                $kItem[] = '`'.$key.'`';
                $dItem[] = $data;
            }
            $field = implode(',', $kItem);
            $values = "'" . implode("','", $dItem) . "'";
            $sql="INSERT INTO `" . DB_PREFIX . "chat_goeasy_list` ($field) VALUES ($values)";
            // ajaxReturn(400,"参数为空",$sql);
            // return $sql;
            $baby=$db->query($sql);
            // $id=$db->insert_id();
            return true;
        }
    }
    // 修改聊天记录(标记已读)
    function upgoeasy($dt){
         if(!$dt){ajaxReturn(404,'参数为空');}
        $user = isLogin();
        @$uid=$user['uid'];
        if(!$uid){ajaxReturn(404,'参数为空,UID');}
        if(@$dt['messageId']){
            $wSql=" `messageId`='".$dt['messageId']."' ";
            $id=$dt['messageId'];
            if(@$dt['isdel']){
                $detail=chatdetails($id,true);
                if(is_array($detail['alldel'])){
                    array_push($detail['alldel'],$uid);
                    $dt["alldel"]= $detail['alldel'];
                }else{
                    $dt['alldel']=[$uid];
                }
                $dt["alldel"]= json_encode($dt["alldel"]);
            }
            unset($dt['messageId']);
            unset($dt['isdel']);
        }else{
            if(@$dt['receiverId']){
                $receiverId=$dt['receiverId'];
                unset($dt['receiverId']);
            }else{
                ajaxReturn(404,'参数为空');
            }
            if(@$dt['senderId']){
                $senderId=$dt['senderId'];
                unset($dt['senderId']);
            }else{
                ajaxReturn(404,'参数为空');
            }
            $wSql=" `receiverId`='$receiverId' AND `senderId`='$senderId' AND `read`='false'";
        }
        $userData=$dt;
        
        // return $dt;
        $Item = array();
        foreach ($userData as $key => $data) {
            $Item[] = "`$key`='$data'";
        }
        $upStr = implode(',', $Item);
        $db = Database::getInstance();
        $sql = "UPDATE `" . DB_PREFIX . "chat_goeasy` SET $upStr  WHERE $wSql ;";
        //   return $sql;
        $query = $db->query($sql);
        
        if($query){
            return true;
        }else{
            return false;
        }
    }
    function isAlldel($uid){
        if(!$uid){
            return "";
        }
        $db = Database::getInstance();
        $sql = "SELECT * FROM  `" . DB_PREFIX . "chat_goeasy`  WHERE  `isdel`='0' AND `alldel` LIKE '%$uid%';";
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data ="";
        foreach ($logs as $key => $v) {
            $data.=" AND `id`!='".$v['id']."' ";
        }
        return $data;
    }
       // 获取用户聊天列表
    function getchatgoeasylist($dt=[]){
        $db = Database::getInstance();
        $user=isLogin();
        $uid=$user['uid'];
            
        @$isAll=$dt['pages']['isAll'];
        
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
        $wSql="";$mySql='';$isfym="";$delSql=isAlldel($uid);
        $bySql="ORDER BY id DESC ";
        if(@$dt['receiverId']){
            $receiverId=$dt['receiverId'];
            unset($dt['receiverId']);
        }else{
            $output['msg']="参数为空";
            return $output;
        }
        if(@$dt['senderId']){
            $senderId=$dt['senderId'];
            unset($dt['senderId']);
        }else{
            $output['msg']="参数为空";
            return $output;
        }
	    $mySql=" AND ( `receiverId`='$receiverId' OR `senderId`='$receiverId' )  AND ( `receiverId`='$senderId' OR `senderId`='$senderId' )  ";
	    
        if(@$dt['chattype']){
            $wSql=" AND `chattype` = ".$dt['chattype']." " ;
        }else{
            $output['msg']="参数为空";
            return $output;
        }
        
        
        $pno = 1;$pgs = intval(Option::get('pagesSize'));
	    if(@$dt['pages']['pno']){
		  $pno = intval($dt['pages']['pno']);
		}
		
		if(@$dt['pages']['pageSize']){
		  $pgs = intval($dt['pages']['pageSize']);
		}
		$output['pages']['pageSize']=$pgs;$output['pages']['pno']=$pno; 
		$totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "chat_goeasy` WHERE  `isdel`='0'   $wSql $mySql $delSql ";
		$res = $db->fetch_array($db->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "chat_goeasy`  WHERE  `isdel`='0'  $wSql $mySql $delSql $bySql $isfym ;";
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $v['user']=$login->getuserByUid($v['create_by']);
            $v['payload']=emoji_decode($v['payload']);
            $v['payload']=json_decode($v['payload'],true);
            $v['alldel']=json_decode($v['alldel'],true);
            $v['read']=zh_boolval($v['read']);
            $v['recalled']=zh_boolval($v['recalled']);
            $v['timestamp']=intval($v['timestamp']);
            $data[]=$v;
        }
        if(@$dt['list']){
            $output['list']=$data;
        }else{  
            $output['list']=array_reverse($data);
        }
        $output['delsql']=$delSql;
        return $output;
    }
    // 获取聊天类容详情
    function chatdetails($id,$istype=false){
        $db = Database::getInstance();
        $wSql="  AND `id`='".$id."' ";
        if($istype){
            $wSql=" AND `messageId`='".$id."'";
        }
        $sql = "SELECT * FROM `" . DB_PREFIX . "chat_goeasy` WHERE  `isdel`='0' $wSql ;";
        $logs = $db->query($sql);
        
        $data = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $v['user']=$login->getuserByUid($v['create_by']);
            $v['payload']=emoji_decode($v['payload']);
            $v['payload']=json_decode($v['payload'],true);
            $v['alldel']=json_decode($v['alldel'],true);
            $v['read']=zh_boolval($v['read']);
            $v['recalled']=zh_boolval($v['recalled']);
            $v['timestamp']=intval($v['timestamp']);
            $data=$v;
        }
        
        return $data;
    }
    // 转换布尔字符串
    function zh_boolval($str){
        if($str=='true'){
            return true;
        }else{
            return false;
        }
    }
    
    // 获取当前聊天的列表
    function getchatlist($dt=[]){
        $db = Database::getInstance();
        $user=isLogin();
        $uid=$user['uid'];
            
        @$isAll=$dt['pages']['isAll'];
        
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
        $wSql="";$mySql='';$isfym="";
        $bySql="ORDER BY update_time DESC ";
        if(@!$uid){
            $output['msg']="参数为空#uid";
            return $output;
        }
	    $mySql=" AND ( `receiverId`='$uid' OR `senderId`='$uid' ) AND `receiverdel`!='$uid' AND `senderdel`!='$uid' ";
	    
        if(@$dt['chattype']){
            $wSql=" AND `chattype` = ".$dt['chattype']." " ;
        }else{
            $output['msg']="参数为空#chattype";
            return $output;
        }
        
        
        $pno = 1;$pgs = intval(Option::get('pagesSize'));
	    if(@$dt['pages']['pno']){
		  $pno = intval($dt['pages']['pno']);
		}
		
		if(@$dt['pages']['pageSize']){
		  $pgs = intval($dt['pages']['pageSize']);
		}
		$output['pages']['pageSize']=$pgs;$output['pages']['pno']=$pno; 
		$totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "chat_goeasy_list` WHERE  `isdel`='0'   $wSql $mySql ";
		$res = $db->fetch_array($db->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
        
        $sql = "SELECT * FROM  `" . DB_PREFIX . "chat_goeasy_list`  WHERE  `isdel`='0'  $wSql $mySql $bySql $isfym ;";
        // return $sql;
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $chatuser=$v['receiverId'];
            $v['isdeltype']="senderdel";
            if($v['receiverId']==$uid){
                $chatuser=$v['senderId'];
                $v['isdeltype']="receiverdel";
            }
            $v['chatuser']=$login->getuserByUid($chatuser);
            $v['user']=$login->getuserByUid($v['create_by']);
            $v['first']=chatdetails($v['first']);
            $v['last']=chatdetails($v['last']);
            $v['read']=chatreadcount($uid);
            $v['path']='/views/chat/index?id='.$chatuser;
            $v['subtext']="";
            if($v['last']['type']=='text'){
                $v['subtext']=$v['last']['payload']['text'];
            }
            if($v['last']['type']=='image'){
                $v['subtext']='[图片]';
            }
            if($v['last']['type']=='video'){
                $v['subtext']='[视频]';
            }
            if($v['last']['type']=='audio'){
                $v['subtext']='[语音]';
            }
            $data[]=$v;
        }
        
        $output['list']=$data;
        return $output;
    }
    
    //指定数组以$keys键值排序
    function array_sort($array,$keys,$type='asc'){
    //$array为要排序的数组,$keys为要用来排序的键名,$type默认为升序排序
        $keysvalue = $new_array = array();
        foreach ($array as $k=>$v){
            $keysvalue[$k] = $v[$keys];
        }
        if($type == 'asc'){
        asort($keysvalue);
        }else{
        arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $k=>$v){
        $new_array[$k] = $array[$k];
        }
        return $new_array;
    }
    
    // 修改聊天会话
    function upchatlist($dt){
         if(!$dt){ajaxReturn(404,'参数为空');}
        $user = isLogin();
        @$uid=$user['uid'];
        if(!$uid){ajaxReturn(404,'参数为空,UID');}
        $userData=$dt;
        if(@$dt['id']){
            $wSql=" `id`='".$dt['id']."' ";
        }
        // return $dt;
        $Item = array();
        foreach ($userData as $key => $data) {
            $Item[] = "`$key`='$data'";
        }
        $upStr = implode(',', $Item);
        $db = Database::getInstance();
        $sql = "UPDATE `" . DB_PREFIX . "chat_goeasy_list` SET $upStr  WHERE $wSql ;";
        //   return $sql;
        $query = $db->query($sql);
        
        if($query){
            return true;
        }else{
            return false;
        }
    }
    
    // 获取用户的数据
    function getuserlist($dt=[],$nosql=""){
        $user = isLogin(true);
        @$uid=$user['uid'];
        
        $db = Database::getInstance();
        @$isAll=$dt['pages']['isAll'];
        
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
        $wSql="";$mySql='';$isfym="";
        $bySql="ORDER BY update_time DESC ";
        
        $pno = 1;$pgs = intval(Option::get('pagesSize'));
        
        $gSql=" AND `gender`='2' ";
        
        if(@$dt['gender']||@$dt['gender']=='0'){
            $gSql=" AND `gender`='".$dt['gender']."' ";
        }
        
        if(@$dt['status']){
            $wSql.=" AND `status`='".$dt['status']."' ";
        }else{
            $wSql.=" AND `status`='0' ";
        }
        if(@$dt['issingle']){
            $wSql.=" AND `issingle`='".$dt['issingle']."' ";
        }else{
            $wSql.=" AND `issingle`='1' ";
        }
        if(@$dt['income']){
            $wSql.=" AND `income`='".$dt['income']."' ";
        }
        if(@$dt['company']){
            $wSql.=" AND `company`='".$dt['company']."' ";
        }
        if(@$dt['marital']){
            $wSql.=" AND `marital`='".$dt['marital']."' ";
        }
        if(@$dt['xueli']){
            $wSql.=" AND `xueli`='".$dt['xueli']."' ";
        }
        if(@$dt['school']){
            $wSql.=" AND `school`='".$dt['school']."' ";
        }
        if(@$dt['position']){
            $wSql.=" AND `position`='".$dt['position']."' ";
        }
        if(@$dt['isrealName']){
            $wSql.=" AND `isrealName`='".$dt['isrealName']."' ";
        }
        if(@$dt['iswork']){
            $wSql.=" AND `iswork`='".$dt['iswork']."' ";
        }
        if(@$dt['isxueli']){
            $wSql.=" AND `isxueli`='".$dt['isxueli']."' ";
        }
        if(@$dt['province']){
            $wSql.=" AND `province`='".$dt['province']."' ";
        }
        if(@$dt['city']){
            $wSql.=" AND `city`='".$dt['city']."' ";
        }
        if(@$dt['district']){
            $wSql.=" AND `district`='".$dt['district']."' ";
        }
        if(@$dt['height']){
            $wSql.=" AND `height`>='".$dt['height']['min']."' AND `height`<='".$dt['height']['max']."' ";
        }
        if(@$dt['weight']){
            $wSql.=" AND `weight`>='".$dt['weight']['min']."' AND `weight`<='".$dt['weight']['max']."' ";
        }
        if(@$dt['birthday']){
            $yearM=31536000;
            $birthdaymin=date('Y-m-d', (time()-($yearM*intval($dt['birthday']['min']))));
            $birthdaymax=date('Y-m-d', (time()-($yearM*intval($dt['birthday']['max']))));
            $wSql.=" AND `birthday`>='".$birthdaymin."' AND `birthday`<='".$birthdaymax."' ";
        }
        
	    if(@$dt['pages']['pno']){
		  $pno = intval($dt['pages']['pno']);
		}
		
		if(@$dt['pages']['pageSize']){
		  $pgs = intval($dt['pages']['pageSize']);
		}
		$output['pages']['pageSize']=$pgs;$output['pages']['pno']=$pno; 
		$totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "user` WHERE  `isdel`='0' $nosql $gSql  $wSql $mySql ";
		$res = $db->fetch_array($db->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
        if(@$dt['lng']&&@$dt['lat']){
            $lng=$dt['lng'];$lat=$dt['lat'];
            $sql = "SELECT *,(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*($lng-lng)/360),2)+COS(PI()*$lat/180)* COS(lat * PI()/180)*POW(SIN(PI()*($lat-lat)/360),2)))) as distance FROM  `" . DB_PREFIX . "user`  WHERE  `isdel`='0' $nosql $gSql  $wSql $mySql $bySql $isfym ;";
        }else{
            $sql = "SELECT * FROM  `" . DB_PREFIX . "user`  WHERE  `isdel`='0' $nosql $gSql  $wSql $mySql $bySql $isfym ;";
        }
        
        // return $sql;
        $logs = $db->query($sql);
        $output['sql']=$sql;
        $data = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $nv=$login->getUserDataByUid($v['uid']);
            @$jl=$v['distance'];
            if($jl){
                $jl=$jl*1000;
                $jl=round($jl,0);
                $dw="m";
                if($jl<1000){$jl=$jl;$dw="m";}else{$jl=round($jl/1000,0);$dw="km";}
                // $nv['juli']=$jl;
                // $nv['dw']=$dw;
                $nv['juli']=$jl.$dw;
            }else{
                // $nv['juli']='';
                // $nv['dw']='';
                $nv['juli']="";
            }
            $data[]=$nv;
        }
        
        $output['list']=$data;
        return $output;
        
    }
    
    // 获取推荐用户列表
    
    function getpushlist($dt=[]){
        $user = isLogin(true);
        @$uid=$user['uid'];
        // $uid=10000;
        $gender=2;
        if(@$user['gender']=='2'){
            $gender=1;
        }
        @$lat=$dt['lat'];
        @$lng=$dt['lng'];
        $isjuli=true;
        if(!$lat){
            $isjuli=false;
        }
        if(!$lng){
            $isjuli=false;
        }
        if($uid){
        // 查看屏蔽用户数量
        $pbdt=[
            "type"=>1,
            "pages"=>[
                "isAll"=>true
                ]
            ];
        $user['shieldUser']=getshieldlist($pbdt,$uid);
        //  return $user;
        $uiddata=$user['shieldUser']['uidlist'];
        }
        
        $puhsNum=json_decode(Option::get('pushNum'),true);
        
        $db = Database::getInstance();
        
        // 用户可以推荐的条数
        $usernum=$puhsNum['num'];
        if(@$user['isvip']){
            $usernum=$puhsNum['vip'];
        }
        $usernum=intval($usernum);
        if($usernum<=0){
            $usernum=1;
        }
        // 今天的日期
        $pushday=date("Y-m-d");
        // 查询是否有推荐
        
        // 推荐的列表
        $pushList=array();
        
        $totalSql = "SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "user_push` WHERE  `isdel`='0' AND `pushday`='$pushday' AND `uid`='".$uid."' ;";
        $res = $db->fetch_array($db->query($totalSql));
        $total=intval($res['total']);
        if($total>=$usernum){
            $sql = "SELECT * FROM `" . DB_PREFIX . "user_push` WHERE  `isdel`='0' AND `pushday`='$pushday' AND `uid`='".$uid."' ORDER BY id DESC  LIMIT 0,1 ;";
            $logs = $db->query($sql);
            $login= new LoginAuth();
            foreach ($logs as $key => $v) {
                $data = array();
                if($v['pushuid']){
                    $v['pushuid']=json_decode($v['pushuid'],true);
                    foreach($v['pushuid'] as $k => $d){
                        $nv= $login->getUserDataByUid($d);
                        if($isjuli){
                            
                            $sql="select (2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*($lng-lng)/360),2)+COS(PI()*$lat/180)* COS(lat * PI()/180)*POW(SIN(PI()*($lat-lat)/360),2)))) as juli  FROM `" . DB_PREFIX . "user`  WHERE uid = '$d' ; ";
                            
                            $res = $db->fetch_array($db->query($sql));
                    		$jl = floatval($res['juli']);
                            
                            
                            $output['sql'] = $sql;
                            $nv['juli']='';
                            // if($jl<1000){$jl=$jl;$dw="米";}elseif($jl<10000){$jl=round($jl/1000,2);$dw="km";}else{$jl=round($jl/10000,2);$dw="万米";}
                            // @$jl=$v['juli'];
                            if($jl){
                                $jl=$jl*1000;
                                $jl=round($jl,0);
                                $dw="米";
                                if($jl<1000){$jl=$jl;$dw="m";}else{$jl=round($jl/1000,0);$dw="km";}
                                // $user['juli']=$jl;
                                // $user['dw']=$dw;
                                $nv['juli']='距你 '.$jl.''.$dw;
                            }
                        }else{
                            $output['lat'] =$lat;
                            $output['lng'] =$lng;
                            $nv['juli']="" ;
                        }
                        $nv['itemtype']="user";
                        if(!in_array($d,$uiddata)){
                            $data[]=$nv;
                        }  
                    }
                }
                $pushList=$data;
            }
        }else{
            $nouidSql="";
            if($total>0){
                if($uid){
                    $sql = "SELECT * FROM `" . DB_PREFIX . "user_push` WHERE  `isdel`='0' AND `pushday`='$pushday' AND `uid`='".$uid."';";
                    $logs = $db->query($sql);
                    foreach ($logs as $key => $v) {
                        $data = array();
                        if($v['pushuid']){
                            $v['pushuid']=json_decode($v['pushuid'],true);
                            foreach($v['pushuid'] as $k => $d){
                                  $nouidSql.=" AND `uid` != '$d' ";
                            }
                        }
                    }
                }
            }
            if(count($uiddata)>0){
                foreach( $uiddata as $k => $d){
                    $nouidSql.=" AND `uid` != '$d' ";
                }
            }
            $udt=[
                "gender"=>$gender,
                "issingle"=>1,
                "lat"=>$lat,
                "lng"=>$lng
                ];
            $userlist=getuserlist($udt,$nouidSql);
            // return $userlist;
            if($userlist['pages']['recordCount']>0){
                $pushuid=[];
                foreach($userlist['list'] as $k => $d){
                    $d['itemtype']="user";
                    $pushList[]=$d;
                    $pushuid[]=$d['uid'];
                }
                if($uid){
                    $addt=[
                        "uid"=>$uid,
                        "update_by"=>$uid,
                        "pushday"=>$pushday,
                        "pushuid"=>json_encode($pushuid)
                    ];
                    $kItem = array();
                    $dItem = array();
                    foreach ($addt as $key => $data) {
                        $kItem[] = '`'.$key.'`';
                        $dItem[] = $data;
                    }
                    $field = implode(',', $kItem);
                    $values = "'" . implode("','", $dItem) . "'";
                    $sql="INSERT INTO `" . DB_PREFIX . "user_push` ($field) VALUES ($values)";
                    // ajaxReturn(400,"参数为空",$sql);
                    // return $sql;
                    $baby=$db->query($sql);
                }
            }
        }
        $manghe=[
            [
            "uid"=>1,
            "img"=>imgUrlpd('/content/images/icon/tuodanhaibao.png'),
            "path"=>'',
            "itemtype"=>'plugin'
            ]
        ];
        $gzh=[
            [
            "uid"=>2,
            "img"=>imgUrlpd('/content/images/icon/tuodanhaibao.png'),
            "path"=>'/plugin/plugins/webview?url=https%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzI2ODUxMzg4Nw%3D%3D%26mid%3D2247485016%26idx%3D1%26sn%3De5f60600ea30f669264ddcf5db4fb080%26chksm%3Deaef2168dd98a87ead60eed0f24e799c1befbfe95e341231216af72315c33a56839f92e69ef9%26token%3D29762947%26lang%3Dzh_CN%23rd',
            "itemtype"=>'plugin'
            ]
        ];
        array_splice($pushList,3,0,$manghe);
        array_splice($pushList,7,0,$gzh);
        $output['list']=$pushList;
        $output['dt']=$dt;
        return $output;
    }
    */
    
    
    
    
    